package extendThread;

/**
 * @author 李泽伟
 */
public class Main {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        MyThread t3 = new MyThread();
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t1.start();
        t2.start();
        t3.start();
    }
}

class MyThread extends Thread {
    private static int ticket = 100;
    private static final Object obj = new Object();
    @Override
    public void run() {
        while (true) {
            synchronized (MyThread.class){
                if (ticket > 0) {
                    try {
                        // 加上sleep之后，进入sleep的线程可能性增大，会造成：线程2卖出了第:-1张票
                        Thread.sleep(0);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName() + "卖出了第:" + ticket + "张票");
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}